<?php
/**
 * User: @lose
 * Date: 2020/7/28
 * Time: 2:02 下午
 */

namespace Beerus\Modules\Store\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\store\StoreAccount as mAccount;
use Biz\service\admin\StoreAccount as sAccount;
use Doraemon\cache\User as cUser;
use Doraemon\model\Member as mMember;
use Doraemon\service\Member;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\StringUtil;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;


class AccountController extends Controller
{
    public function index(Content $content, Request $request)
    {
        Admin::script($this->setScript());
        $page = $request->input('page', 1);
        $perPage = $request->input('per_page', 20);
        $condition = self::GeTCondition($request);
        $limit = [
            ($page - 1) * $perPage, $perPage
        ];
        $result = sAccount::getList($condition, $limit);
        $grid = new pGridDataModel($result['list'], $result['total'], [
            'per_page' => $perPage
        ]);

        $gridList = Admin::grid($grid,
            function (Grid $grid) {
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->filter(function ($filter) {
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();
                    // 在这里添加字段过滤器
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('uid', 'uid')->placeholder('用户uid');
                        $filter->equal('server_type', '服务商类型')->select(mAccount::SERVER_TYPE_MAP);
                    });
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('store_id', '门店id')->placeholder('门店id');
                        $filter->equal('auth_status', '认证状态')->select(mAccount::AUTH_MAP);
                    });
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('store_name', '门店名称')->placeholder('门店名称');
                        $filter->equal('is_test', '测试号')->select([0 => '否', 1 => '是']);
                    });
                    $filter->expand();//默认展开
                });

                $grid->column("uid", '用户uid');
                $grid->column("store_id", '门店id');
                $grid->column("store_name", '门店名称')->display(function () {
                    $html = '<span>' . $this->store_name . '</span><br>';
                    if ($this->is_test) {
                        $html .= '<br><span class="label label-warning">测试号</span>';
                    }
                    return $html;
                });

                $grid->column('server_type', '服务商类型');
                $grid->column("auth_status_name", '状态')->display(function ($title, Grid\Column $column) {

                    $html = '';
                    $pos = $this->auth_status;
                    $map = ['label-primary', 'label-warning', 'label-success', 'label-info', 'label-danger'];
                    $html .= ' <span class="label ' . $map[$pos] . '">' . $this->auth_status_name . '</span><br/><br/>';

                    if ($this->complete_status == 1) {
                        $map = ['label-info', 'label-danger'];
                        $html .= ' <span class="label ' . $map[$pos] . '">信息不完整</span>';
                    }
                    return $html;
                });
                $grid->column("admin_id", '处理人')->display(function () {
                    if (!$this->admin_id) {
                        return '-';
                    } else {
                        return Admin::user()->find($this->admin_id)->name;
                    }
                })->width(60);;
                $grid->column("edittime", '操作时间');
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableView();
                    $actions->disableDelete();
                    if ($actions->row->complete_status == 1) {
                        $actions->disableEdit();
                        $actions->prepend('&nbsp;<a class="fa fa-address-book" target="" href=\'/admin/store/basic/index/create/' . $actions->row->id . '\' ">完整数据</a>');
                    }

                    if ($actions->row->complete_status != 1 && $actions->row->auth_status == mAccount::AUTH_DEFAULT) {
                        $actions->prepend('&nbsp;<a class="fa fa-address-book" target="" href=\'/admin/store/order/create/' . $actions->row->id . '\' ">添加账单</a>');
                    }
                    if ($actions->row->is_test == 0) {
                        $actions->prepend('<p><a class="settest label label-primary " data-id="' . $actions->row->id . '"  href="javascript:void(0);">设置为测试账户</a></p>');
                    } else {
                        $actions->prepend('<p><a class="setnormal label  label-default" data-id="' . $actions->row->id . '"  href="javascript:void(0);">恢复正常账户</a></p>');

                    }


                });
            });
        $content->row($gridList);
        return $content
            ->header('门店基础信息')
            ->description(' ')
            ->breadcrumb(['text' => 'user']);
    }


    public function GeTCondition($request)
    {

        $condition = [];
        if ($request->input('uid')) {
            $condition['uid'] = $request->input('uid');
        }

        if ($request->input('store_id')) {
            $condition['store_id'] = $request->input('store_id');
        }

        if ($request->input('store_name')) {
            $condition['store_name'] = $request->input('store_name');
        }

        if ($request->input('auth_status') != '' && $request->input('auth_status') != 4) {
            $condition['auth_status'] = $request->input('auth_status');
        }

        if ($request->input('server_type')) {
            $condition['server_type'] = $request->input('server_type');
        }
        if ($request->input('is_test') != null && strlen($request->input('is_test')) > 0) {
            $condition['is_test'] = $request->input('is_test') ? 1 : 0;
        }

        return $condition;
    }

    public function createAccount(Content $content, Request $request, $id = 0)
    {
        $account_info = mAccount::getInfo($id);
        $account_info['type'] = 'create';
        $form = new Form($account_info);
        if ($account_info['id']) {
            $form->hidden('id');
            $form->html('<div class="btn-group pull-right">
                <button  class="btn btn-info  pull-right"><a style="color:#f4f4f4" href="/admin/store/basic/createAuth/' . $id . '">下一步</a></button>
                </div>');

        }
        $form->hidden('type');
        $form->text('auth_phone', '认证手机号')->width("300px")->required();
        if ($account_info['id']) {
            $form->text('uid', '账户uid')->width("300px")->required()->readonly();
        } else {
            $form->text('uid', '账户uid')->width("300px")->required();
        }
        $form->text('store_name', '门店名称')->width("300px")->help("门店名称为最终的门店账户名称，请认真填写，最多14个字")->required();
        $form->select('is_board_brand', "是否进口门店")->options(mAccount::BOARD_MAP);
        $form->select("store_category", '门店分类')->options(array_combine(mAccount::CATEGORY_MAP, mAccount::CATEGORY_MAP))->width("300px")->required();
        $form->disableReset();
        $form->action('/admin/store/basic/account/save');

        return $content
            ->header('账户信息')
            ->row($form);
    }


    public function saveAccount(Request $request, $id = 0)
    {
        $params = $request->all();
        try {
            $uid = $params['uid'];
            $a_id = $params['id'];
            $auth_phone = $params['auth_phone'];
            $store_name = $params['store_name'];
            $is_exist = Member::phoneExists($uid, $auth_phone);
            if (!$is_exist) {
                $error = new MessageBag([
                    'title' => '用户电话号码不对'
                ]);
                return back()->with(compact('error'));
            }
            if (empty($store_name)) {
                $error = new MessageBag([
                    'title' => '门店名称必填'
                ]);
                return back()->with(compact('error'));
            }
            if (StringUtil::strlen($store_name) > 14) {
                $error = new MessageBag([
                    'title' => '门店名称超出长度'
                ]);
                return back()->with(compact('error'));
            }
            $type = $params['type'] ?: '';
            $is_board_brand = $params['is_board_brand'];
            $store_category = $params['store_category'];
            $data = [
                'uid' => $uid,
                'auth_phone' => $auth_phone,
                'store_name' => $store_name,
                'store_category' => $store_category,
                'is_board_brand' => $is_board_brand,
                'admin_id' => Admin::user()->id,
            ];

            //检查是否有此uid的账户
            if ($a_id) {
                $data['edittime'] = date("y-m-d H:i:s", time());
                $rs = mAccount::updateById($a_id, $data);
                //更新主账户类别，普通用户改变类别，品牌用户不用改变类别
                cUser::deleteUserInfo($uid);
                $success = new MessageBag([
                    'title' => '修改成功'
                ]);
            } else {
                //检查是否有此uid的账户
                $info = mAccount::getInfoByWhere(['uid' => $uid]);
                if ($info && is_array($info)) {
                    $error = new MessageBag([
                        'title' => '此用户uid 已有门店账户'
                    ]);
                    return back()->with(compact('error'));
                }
                $data['addtime'] = date("y-m-d H:i:s", time());
                $data['edittime'] = date("y-m-d H:i:s", time());
                $rs = mAccount::add($data);
                $a_id = $rs;
                //创建store_basic
                $success = new MessageBag([
                    'title' => '添加成功'
                ]);
            }
            mMember::updateUserInfo($uid, ['nick' => $store_name]);
            // 标记用户强制退出
            sAccount::createStoreBasic($a_id, $uid, $store_name, $store_category);
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '请重试,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
        if ($type) {
            return redirect('/admin/store/basic/index/create/' . $a_id)->with(compact('success'));
        } else {
            return redirect('/admin/store/basic/index/' . $a_id . '/edit')->with(compact('success'));
        }
    }


    public function editStore(Request $request, Content $content, $id = 0, $type = '')
    {
        $tab = new Tab();
        $type = $type ?: 'account';
        if ($type == 'account') {
            $tab->add('账户信息', self::listAction($type, $id), true);
            $tab->addLink('门店认证信息', '/admin/store/basic/index/' . $id . '/edit/auth', false);
            $tab->addLink('运营者信息', '/admin/store/basic/index/' . $id . '/edit/oprator', false);
        }
        if ($type == 'oprator') {
            $tab->addlink('账户信息', '/admin/store/basic/index/' . $id . '/edit', false);
            $tab->addLink('门店认证信息', '/admin/store/basic/index/' . $id . '/edit/auth', false);
            $tab->add('运营者信息', self::listAction($type, $id), true);
        }
        if ($type == 'auth') {
            $tab->addlink('账户信息', '/admin/store/basic/index/' . $id . '/edit', false);
            $tab->add('门店认证信息', self::listAction($type, $id), true);

            $tab->addLink('运营者信息', '/admin/store/basic/index/' . $id . '/edit/oprator', false);
        }

        return $content
            ->breadcrumb(
                ['text' => '门店基础信息', 'url' => '/store/basic/index'],
                ['text' => '编辑门店基础信息']
            )
            ->body($tab);
    }


    public function listAction($type, $id)
    {
        $account_info = mAccount::getInfo($id);
        if ($type == 'account') {
            $form = new Form($account_info);
            $form->hidden('id');
            $form->text('auth_phone', '认证手机号')->width("300px")->required();
            $form->text('uid', '账户uid')->width("300px")->required()->readonly();
            $form->text('store_name', '门店名称')->width("300px")->help("门店名称为最终的门店账户名称，请认真填写，最多14个字")->required();
            $form->select('is_board_brand', "是否进口门店")->options(mAccount::BOARD_MAP);
            $form->select("store_category", '门店分类')->options(array_combine(mAccount::CATEGORY_MAP, mAccount::CATEGORY_MAP))->width("300px")->required();
            $form->disableReset();
            $form->action('/admin/store/basic/account/save');
        }
        if ($type == 'auth') {

            $auth_info = sAccount::getAuthByAId($account_info['id']);
            $auth_info['account_id'] = $account_info['id'];

            $form = new Form($auth_info);
            $form->hidden('account_id');
            $form->hidden('id');

            $form->fieldChange('server_type', '服务商类型', $form)
                ->options(mAccount::SERVER_TYPE_MAP)
                ->default(mAccount::BRAND_TYPE)
                ->callablePreCommon(function (Form $form) {
                })->callableMap([
                    mAccount::BRAND_TYPE => function (Form $form) {
                        $form->text('company_name', '企业名称')->width("300px")->rules('required|max:20');
                        $form->imgUpload('business_license_pic', '企业营业执照', false, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG]);
                        $form->datetime('license_period', '营业执照有效期')->required();
                        $form->imgUpload('opening_pic', '开户许可证', false, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG]);
                        $form->imgUpload('front_card_pic', '身份证正面', false, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG]);
                        $form->imgUpload('behind_card_pic', '身份证背面', false, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG]);
                        $form->imgUpload('trademark_regist_pic', '商标注册证', true, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG])->help("最多可传6张");
                        $form->imgUpload('product_quality_pic', '产品质检图片', true, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG])->help("最多可传15张");
                    },
                    mAccount::AGENT_TYPE => function (Form $form) {
                        $form->text('company_name', '企业名称')->width("300px")->required();
                        $form->imgUpload('business_license_pic', '企业营业执照', false, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG]);
                        $form->datetime('license_period', '营业执照有效期')->required();
                        $form->imgUpload('opening_pic', '开户许可证', false, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG]);
                        $form->imgUpload('front_card_pic', '身份证正面', false, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG]);
                        $form->imgUpload('behind_card_pic', '身份证背面', false, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG]);
                        $form->imgUpload('trademark_regist_pic', '商标注册证', true, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG])->help("最多可传6张");
                        $form->imgUpload('trademark_transfer_pic', '商标授权书', true, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG])->help("最多可传4张");
                        $form->imgUpload('product_quality_pic', '产品质检图片', true, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG])->help("最多可传15张");
                    },
                ]);
            $form->disableReset();
            $form->action('/admin/store/basic/auth/save');
        }
        if ($type == 'oprator') {
            $oprator_info = sAccount::getOperatorByAId($id);
            $oprator_info['account_id'] = $account_info['id'];
            $form = new Form($oprator_info);
            $form->hidden('account_id');
            if ($oprator_info) {
                $form->hidden('id');
            }
            $form->text('name', '姓名')->width("300px")->required();
            $form->text('phone', '电话号码')->width("300px")->required();
            $form->text('email', '邮箱')->width("300px")->required();
            $form->text('wx_id', '微信id')->width("300px")->required();
            $form->disableReset();
            $form->action('/admin/store/basic/oprator/save');
        }

        return $form;
    }


    public function createOperator(Content $content, Request $request, $a_id = 0)
    {
        $operator_info = sAccount::getOperatorByAId($a_id);
        $operator_info['account_id'] = $a_id;
        $operator_info['type'] = 'create';
        $form = new Form($operator_info);
        $form->hidden('account_id');
        if ($operator_info) {
            $form->hidden('id');
            $form->html('<div class="btn-group pull-right">
                <button  class="btn btn-info  pull-right"><a style="color:#f4f4f4" href="/admin/store/basic/index">返回门店基础信息</a></button>
                </div>');
        }
        $form->hidden('type');
        $form->text('name', '姓名')->width("300px")->required();
        $form->text('phone', '电话号码')->width("300px")->required();
        $form->text('email', '邮箱')->width("300px")->required();
        $form->text('wx_id', '微信id')->width("300px")->required();
        $form->disableReset();
        $form->action('/admin/store/basic/oprator/save');

        return $content
            ->header('账户信息')
            ->row($form);
    }


    public function saveOprator(Request $request)
    {
        $params = $request->all();
        try {
            $id = $params['id'];
            $name = $params['name'];
            $account_id = $params['account_id'];
            $phone = $params['phone'];
            $email = $params['email'];
            $wx_id = $params['wx_id'];
            $type = $params['type'];
            if (!preg_match("/^1[34578]{1}\d{9}$/", $phone)) {
                throw new \Exception('电话号码不对');
            }
            $data = [
                'account_id' => $account_id,
                'phone' => $phone,
                'name' => $name,
                'email' => $email,
                'wx_id' => $wx_id,
                'admin_id' => Admin::user()->id,
            ];
            if ($id) {
                $data['edittime'] = date("y-m-d H:i:s", time());
                $rs = sAccount::updateOperator($data, $id);
                $success = new MessageBag([
                    'title' => '修改成功'
                ]);
            } else {
                $data['addtime'] = date("y-m-d H:i:s", time());
                $data['edittime'] = date("y-m-d H:i:s", time());
                $rs = sAccount::InsertOperator($data);
                $success = new MessageBag([
                    'title' => '添加成功'
                ]);
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '请重试,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }

        if ($type) {
            return redirect('/admin/store/basic/createOperator/' . $account_id)->with(compact('success'));
        } else {
            return redirect('/admin/store/basic/index')->with(compact('success'));
        }
    }


    public function createAuth(Content $content, Request $request, $a_id = 0)
    {
        $auth_info = sAccount::getAuthByAId($a_id);
        $auth_info['account_id'] = $a_id;
        $auth_info['type'] = 'create';


        $form = new Form($auth_info);

        if ($auth_info) {
            $form->hidden('id');
            $form->html('<div class="btn-group pull-right">
                <button  class="btn btn-info  pull-right"><a style="color:#f4f4f4" href="/admin/store/basic/createOperator/' . $a_id . '">下一步</a></button>
                </div>');

        }
        $form->hidden('account_id');
        $form->hidden('type');


        $form->fieldChange('server_type', '服务商类型', $form)
            ->options(mAccount::SERVER_TYPE_MAP)
            ->default(mAccount::BRAND_TYPE)
            ->callablePreCommon(function (Form $form) {
            })->callableMap([
                mAccount::BRAND_TYPE => function (Form $form) {
                    $form->text('company_name', '企业名称')->width("300px")->required();
                    $form->imgUpload('business_license_pic', '企业营业执照', false, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG]);
                    $form->datetime('license_period', '营业执照有效期')->required();
                    $form->imgUpload('opening_pic', '开户许可证', false, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG]);
                    $form->imgUpload('front_card_pic', '身份证正面', false, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG]);
                    $form->imgUpload('behind_card_pic', '身份证背面', false, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG]);
                    $form->imgUpload('trademark_regist_pic', '商标注册证', true, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG])->help("最多可传6张");
                    $form->imgUpload('product_quality_pic', '产品质检图片', true, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG])->help("最多可传15张");
                },
                mAccount::AGENT_TYPE => function (Form $form) {
                    $form->text('company_name', '企业名称')->width("300px")->required();
                    $form->imgUpload('business_license_pic', '企业营业执照', false, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG]);
                    $form->datetime('license_period', '营业执照有效期')->required();
                    $form->imgUpload('opening_pic', '开户许可证', false, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG]);
                    $form->imgUpload('front_card_pic', '身份证正面', false, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG]);
                    $form->imgUpload('behind_card_pic', '身份证背面', false, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG]);
                    $form->imgUpload('trademark_regist_pic', '商标注册证', true, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG])->help("最多可传6张");;
                    $form->imgUpload('trademark_transfer_pic', '商标授权书', true, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG])->help("最多可传4张");
                    $form->imgUpload('product_quality_pic', '产品质检图片', true, ['imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG])->help("最多可传15张");
                },
            ]);
        $form->disableReset();
        $form->action('/admin/store/basic/auth/save');
        return $content
            ->header('认证信息')
            ->row($form);
    }


    public function saveAuth(Request $request)
    {
        $params = $request->all();
        try {
            $id = $params['id'];
            $company_name = $params['company_name'];
            $server_type = $params['server_type'];
            $business_license_pic = $params['business_license_pic'] ?: '';
            $license_period = $params['license_period'] ?: "";
            $trademark_regist_pic = $params['trademark_regist_pic'] ?: '';
            $trademark_transfer_pic = $params['trademark_transfer_pic'] ?: '';
            $product_quality_pic = $params['product_quality_pic'] ?: '';
            $front_card_pic = $params['front_card_pic'] ?: '';
            $behind_card_pic = $params['behind_card_pic'] ?: '';
            $opening_pic = $params['opening_pic'] ?: '';
            $account_id = $params['account_id'];
            $type = $params['type'];
            if (StringUtil::strlen($company_name) > 20) {
                $error = new MessageBag([
                    'title' => '企业名称超出长度'
                ]);
                return back()->with(compact('error'));
            }

            if (empty($front_card_pic) || empty($behind_card_pic)) {
                throw new \Exception('身份证信息缺失');
            }
            if (strtotime($license_period) < time()) {
                throw new \Exception('执照有效期错误');
            }
            if (empty($opening_pic)) {
                throw new \Exception('开户许可证缺失');
            }
            if (empty($business_license_pic)) {
                throw new \Exception('营业执照缺失');
            }

            if (count(array_filter(explode(",", $trademark_regist_pic))) > 6) {
                throw new \Exception('商标注册证最多6张');
            }

            if (count(array_filter(explode(",", $product_quality_pic))) > 15) {
                throw new \Exception('产品质检报告最多15张');
            }

            if ($server_type == mAccount::AGENT_TYPE) {
                if (empty($trademark_regist_pic)) {
                    throw new \Exception('商标注册证缺失');
                }
                if (empty($trademark_transfer_pic)) {
                    throw new \Exception('商标授权书缺失');
                }
                if (count(explode(",", $trademark_transfer_pic)) > 4) {
                    throw new \Exception('商标授权书最多4张');
                }

                if (empty($product_quality_pic)) {
                    throw new \Exception('产品质检报告缺失');
                }

            }
            $data = [
                'account_id' => $account_id,
                'server_type' => $server_type,
                'company_name' => $company_name,
                'business_license_pic' => $business_license_pic,
                'license_period' => $license_period,
                'trademark_regist_pic' => $trademark_regist_pic,
                'trademark_transfer_pic' => $trademark_transfer_pic,
                'product_quality_pic' => $product_quality_pic,
                'front_card_pic' => $front_card_pic,
                'behind_card_pic' => $behind_card_pic,
                'opening_pic' => $opening_pic,
                'admin_id' => Admin::user()->id,
            ];
            mAccount::updateById($account_id, ['server_type' => $server_type]);
            if ($id) {
                $data['edittime'] = date("y-m-d H:i:s", time());
                sAccount::updateAuth($data, $id);
                $success = new MessageBag([
                    'title' => '修改成功'
                ]);
            } else {
                $data['addtime'] = date("y-m-d H:i:s", time());
                $data['edittime'] = date("y-m-d H:i:s", time());
                $id = sAccount::InsertAuth($data);
                $success = new MessageBag([
                    'title' => '添加成功'
                ]);
            }

        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '请重试,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }

        if ($type) {
            return redirect('/admin/store/basic/createAuth/' . $account_id)->with(compact('success'));
        } else {
            return redirect('/admin/store/basic/index/' . $account_id . '/edit/auth')->with(compact('success'));
        }
    }

    /*设置测试账户
    * */
    public function setTest(Request $request, $id)
    {

        try {
            $account_info = mAccount::getInfo($id);
            if (empty($account_info)) {
                throw new \Exception('账户不存在！');
            }
            $store_id = $account_info['store_id'];
            //设置测试账户
            if ($store_id) {
                sAccount::updateStoreBasic($store_id, ['is_test' => mAccount::TEST_ACCOUNT]);
                $rs = mAccount::updateById($id, ['is_test' => mAccount::TEST_ACCOUNT]);
            }
            //图片设置为仅自己可见
            if ($rs) {
                $status = true;
                $message = '操作成功';
            } else {
                $status = false;
                $message = '操作失败';
            }
        } catch (\Exception $e) {
            $status = false;
            $message = $e->getMessage();
        }
        $success = new MessageBag([
            'title' => '操作成功'
        ]);
        return response()->json(compact('status', 'message'));
    }

    /*设置测试账户
 * */
    public function setNormal(Request $request, $id)
    {

        try {
            $account_info = mAccount::getInfo($id);
            if (empty($account_info)) {
                throw new \Exception('账户不存在！');
            }
            $store_id = $account_info['store_id'];
            //设置测试账户
            if ($store_id) {
                sAccount::updateStoreBasic($store_id, ['is_test' => mAccount::NOT_TEST_ACCOUNT]);
                $rs = mAccount::updateById($id, ['is_test' => mAccount::NOT_TEST_ACCOUNT]);
            }
            //图片设置为仅自己可见
            if ($rs) {
                $status = true;
                $message = '操作成功';
            } else {
                $status = false;
                $message = '操作失败';
            }
        } catch (\Exception $e) {
            $status = false;
            $message = $e->getMessage();
        }
        $success = new MessageBag([
            'title' => '操作成功'
        ]);
        return response()->json(compact('status', 'message'));
    }

    /*设置scirpt
     *
     * */
    private function setScript()
    {
        return <<<SCRIPT

        //设置测试
         $('.settest').unbind('click').click(function(){
            var id= $(this).data('id');
            layer.confirm('确定要设置为测试么？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                 let url = '/admin/store/basic/setTest/'+ id;
                let params = {};
                $.post(url, params , function (result) {
                    if (result.status == 1) {
                        layer.msg(result.message);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.message);
                    }
                });
            });
        });
        
          $('.setnormal').unbind('click').click(function(){
            var id= $(this).data('id');
            layer.confirm('确定要恢复正常账户么？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                 let url = '/admin/store/basic/setNormal/'+ id;
                let params = {};
                $.post(url, params , function (result) {
                    if (result.status == 1) {
                        layer.msg(result.message);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.message);
                    }
                });
            });
        });
SCRIPT;
    }


}